<template>
  <view class="container">
    <view class="category-layout">
      <!-- 左侧分类菜单 -->
      <view class="category-menu">
        <view 
          class="category-item"
          :class="{ active: selectedCategory.id === category.id }"
          v-for="category in categories"
          :key="category.id"
          @click="selectCategory(category)"
        >
          <text class="category-name">{{ category.name }}</text>
        </view>
      </view>

      <!-- 右侧内容 -->
      <view class="category-content">
        <!-- 当前分类信息 -->
        <view v-if="selectedCategory.id" class="current-category">
          <image :src="selectedCategory.iconUrl || '/static/images/default-category.png'" class="category-icon" />
          <view class="category-info">
            <text class="category-title">{{ selectedCategory.name }}</text>
            <text class="category-desc">{{ selectedCategory.description || '暂无描述' }}</text>
          </view>
        </view>

        <!-- 子分类 -->
        <view v-if="childCategories.length > 0" class="sub-categories">
          <view class="section-title">子分类</view>
          <view class="sub-category-grid">
            <view 
              class="sub-category-item"
              v-for="subCategory in childCategories"
              :key="subCategory.id"
              @click="goToProductList(subCategory)"
            >
              <image :src="subCategory.iconUrl || '/static/images/default-category.png'" class="sub-category-icon" />
              <text class="sub-category-name">{{ subCategory.name }}</text>
            </view>
          </view>
        </view>

        <!-- 商品列表 -->
        <view class="products-section">
          <view class="section-header">
            <text class="section-title">商品列表</text>
            <view class="filter-buttons">
              <text 
                class="filter-btn"
                :class="{ active: sortType === 'default' }"
                @click="changeSort('default')"
              >默认</text>
              <text 
                class="filter-btn"
                :class="{ active: sortType === 'price' }"
                @click="changeSort('price')"
              >价格</text>
              <text 
                class="filter-btn"
                :class="{ active: sortType === 'sales' }"
                @click="changeSort('sales')"
              >销量</text>
            </view>
          </view>

          <view class="product-list">
            <product-card 
              v-for="product in products"
              :key="product.id"
              :product="product"
              @cart-updated="onCartUpdated"
            />
          </view>

          <!-- 加载更多 -->
          <view v-if="loading" class="loading">
            <text>加载中...</text>
          </view>
          <view v-if="hasMore && !loading" class="load-more" @click="loadMore">
            <text>加载更多</text>
          </view>
          <view v-if="!hasMore && products.length > 0" class="no-more">
            <text>没有更多了</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { categoryApi, productApi } from '@/api/index.js';
import common from '@/utils/common.js';
import ProductCard from '@/components/product-card.vue';

// 响应式数据
const categories = ref([]);
const selectedCategory = ref({});
const childCategories = ref([]);
const products = ref([]);
const loading = ref(false);
const hasMore = ref(true);
const page = ref(1);
const pageSize = ref(10);
const sortType = ref('default');

// 加载分类
const loadCategories = async () => {
  try {
    common.showLoading('加载中...');
    const res = await categoryApi.getCategoryTree();
    categories.value = res.data || [];
    
    if (categories.value.length > 0) {
      selectCategory(categories.value[0]);
    }
  } catch (error) {
    console.error('加载分类失败:', error);
    common.showError('加载分类失败');
  } finally {
    common.hideLoading();
  }
};

// 选择分类
const selectCategory = async (category) => {
  selectedCategory.value = category;
  childCategories.value = [];
  products.value = [];
  page.value = 1;
  hasMore.value = true;
  
  try {
    // 加载子分类
    const childRes = await categoryApi.getChildCategories(category.id);
    childCategories.value = childRes.data || [];
    
    // 加载商品
    await loadProducts();
  } catch (error) {
    console.error('加载分类数据失败:', error);
    common.showError('加载失败');
  }
};

// 加载商品
const loadProducts = async () => {
  if (loading.value || !hasMore.value) return;
  
  try {
    loading.value = true;
    
    const params = {
      categoryId: selectedCategory.value.id,
      page: page.value,
      pageSize: pageSize.value
    };
    
    // 添加排序参数
    if (sortType.value === 'price') {
      params.sortBy = 'price';
      params.sortOrder = 'asc';
    } else if (sortType.value === 'sales') {
      params.sortBy = 'salesCount';
      params.sortOrder = 'desc';
    }
    
    const res = await productApi.getProductsByCategory(selectedCategory.value.id, params);
    const newProducts = res.data || [];
    
    if (page.value === 1) {
      products.value = newProducts;
    } else {
      products.value = [...products.value, ...newProducts];
    }
    
    hasMore.value = newProducts.length === pageSize.value;
    page.value++;
    
  } catch (error) {
    console.error('加载商品失败:', error);
    common.showError('加载商品失败');
  } finally {
    loading.value = false;
  }
};

// 加载更多
const loadMore = async () => {
  await loadProducts();
};

// 改变排序
const changeSort = (newSortType) => {
  if (sortType.value === newSortType) return;
  
  sortType.value = newSortType;
  page.value = 1;
  hasMore.value = true;
  loadProducts();
};

// 跳转到商品列表
const goToProductList = (category) => {
  uni.navigateTo({
    url: `/pages/product/list?categoryId=${category.id}&categoryName=${category.name}`
  });
};

// 购物车更新事件
const onCartUpdated = () => {
  // 购物车更新事件处理
};

// 生命周期
onMounted(() => {
  loadCategories();
});

onShow(() => {
  // 每次显示页面时刷新商品列表，以便更新购物车状态等
  if (selectedCategory.value && selectedCategory.value.id) {
    page.value = 1;
    loadProducts();
  }
});
</script>

<style scoped>
.container {
  height: 100vh;
  background: #f5f5f5;
}

.category-layout {
  display: flex;
  height: 100%;
}

.category-menu {
  width: 200rpx;
  background: #fff;
  border-right: 1rpx solid #e0e0e0;
  overflow-y: auto;
}

.category-item {
  padding: 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  text-align: center;
}

.category-item.active {
  background: #667eea;
  color: #fff;
}

.category-name {
  font-size: 28rpx;
}

.category-content {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
}

.current-category {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}

.category-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.category-info {
  flex: 1;
}

.category-title {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.category-desc {
  font-size: 24rpx;
  color: #666;
}

.sub-categories {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.sub-category-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.sub-category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 10rpx;
}

.sub-category-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-bottom: 10rpx;
}

.sub-category-name {
  font-size: 24rpx;
  color: #333;
  text-align: center;
}

.products-section {
  background: #fff;
  border-radius: 12rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.filter-buttons {
  display: flex;
  gap: 20rpx;
}

.filter-btn {
  padding: 10rpx 20rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 20rpx;
  font-size: 24rpx;
  color: #666;
}

.filter-btn.active {
  background: #667eea;
  color: #fff;
  border-color: #667eea;
}

.product-list {
  display: grid;
  grid-template-columns: calc(50% - 5rpx) calc(50% - 5rpx);
  gap: 8rpx;
}

.loading,
.load-more,
.no-more {
  text-align: center;
  padding: 30rpx;
  color: #999;
}

.load-more {
  cursor: pointer;
}
</style> 